<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <div slot="after">
          <el-button type="success" @click="$router.push('/import?type=user')">导入</el-button>
          <el-button type="warning" @click="exportData">导出</el-button>
          <el-button type="primary" :disabled="!checkPermission('aaa')" @click="showDialog = true">新增员工</el-button>
        </div>
      </PageTools>
      <el-card v-loading="loading">
        <el-table :data="list">
          <!-- sortable 是增加排序的意思 -->
          <el-table-column type="index" label="序号" sortable="" />
          <el-table-column prop="username" label="姓名" sortable="" align="center" />
          <el-table-column label="头像" width="120px" align="center">
            <template v-slot="{ row }">
              <img
                v-imeagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column prop="formOfEmployment" label="聘用形式" sortable="" :formatter="formatEmployment" />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable="">
            <template slot-scope="obj">
              {{ obj.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column prop="enableState" label="账户状态" sortable="">
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="deleteEmployeeList(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 放置分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev,pager,next"
            :total="page.total"
            :page-size="page.size"
            :current-page="page.page"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" />
      <el-dialog
        title="二维码"
        :visible.sync="showCodeDialog"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
    <assing-role ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, deleteEmployeeList } from '@/api/empliyees'
// 引入枚举数据
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssingRole from './components/assing-role.vue'
// 导入时间格式化文件
import { formatDate } from '@/filters/index'
// 引入二维码插件
import Qrcode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssingRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1, // 起始页面
        size: 10, // 每页条数
        total: 0 // 总数
      },
      loading: false, // 进度条开关
      showDialog: false,
      showCodeDialog: false, // 通知二维码的开关
      showRoleDialog: false, // 角色弹层开关
      userId: null
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    // newPage是最新的页码
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
    //   console.log(cellValue)
      // 找到1所对应的值 find遍历查询
      const obj = EmployeeEnum.hireType.find(item => {
        // console.log(item.id)
        return item.id === parseInt(cellValue) // 将字符串改为数值 不然不相等
      })
      //   console.log(obj)
      return obj ? obj.value : '未知'
    },
    async deleteEmployeeList(id) {
      try {
        await this.$confirm('是否确定删除此员工', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
        await deleteEmployeeList(id)
        this.getEmployeeList() // 重新获取数据
        this.$message.success('删除成功')
      } catch (err) {
        console.log(err)
      }
    },
    exportData() {
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职如期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 导出excel 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // 因为导出文件的数据需要是全部的数据 所以这里需要请求全部员工的数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total }) // 参数是 表头数据 以及 总数
        const data = this.formatJson(headers, rows) // 获取表单中的数据
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        // excel是引入文件的导出对象
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 Object.keys是指拿到数据中的中文key
          data: data, // 对应的数据
          filename: '员工工资表', // 文件名称
          multiHeader, // 复杂表头的部分
          merges // 合并表格部门

        })
      })
    },
    formatJson(headers, rows) {
      // 首先先遍历数组
      return rows.map(item => { // 遍历接口数据
        return Object.keys(headers).map(key => { // 遍历表头数据
        // 文件时间格式的处理
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            // 经行格式化
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            const obj = EmployeeEnum.hireType.find(obj1 => obj1.id === parseInt(item[headers[key]]))
            return obj ? obj.value : '未知'
          }
          return item[headers[key]] // 得到的是每个key对应的值数组
        })
      })
    },
    showQrCode(url) {
      // 判断用户是否有上传头像
      if (url) {
        this.showCodeDialog = true // 打开二维码 此时数据更新了 但是弹层不会立刻执行，因为它是异步渲染
        // 可以使用 $nextTick 方法来解决异步渲染的问题
        this.$nextTick(() => {
          Qrcode.toCanvas(this.$refs.myCanvas, url)
        })
      } else {
        this.$message.warning('该用户还未上传头像')
      }
    },
    async editRole(id) { // 点机角色触发方法
      await this.$refs.assignRole.getUserDetailById(id) // 父组件调用子组件的方法
      this.userId = id // 将DOM元素上的id赋值给userId
      this.showRoleDialog = true // props 传值 打开弹层
    }
  }
}
</script>

<style>

</style>
